import { userLogin, userPhoneLogin, userReg, getMyInfo, getSidebars } from '@/api/login'
import { getToken, setToken, removeToken, getSystem, setTokenType, setUserInfo } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  tokenType: '',
  introduction: '',
  roles: [],
  sidebars: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_TOKEN_TYPE: (state, tokenType) => {
    state.tokenType = tokenType
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_SIDEBARS: (state, sidebars) => {
    state.sidebars = sidebars
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, captcha, captcha_key, type, declare_id } = userInfo
    return new Promise((resolve, reject) => {
      userLogin({ username: username.trim(), password: password, captcha: captcha, captcha_key: captcha_key, type: type, declare_id: declare_id }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.access_token)
        commit('SET_TOKEN_TYPE', data.token_type)
        setToken(data.access_token)
        setTokenType(data.token_type)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user login
  smslogin({ commit }, userInfo) {
    const { code, key, phone } = userInfo
    return new Promise((resolve, reject) => {
      userPhoneLogin({ phone: phone, code: code, key: key }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.access_token)
        commit('SET_TOKEN_TYPE', data.token_type)
        setToken(data.access_token)
        setTokenType(data.token_type)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  reg({ commit }, userInfo) {
    const { username, password, code, key, user_type, org_name, phone, org_status, contact_name } = userInfo
    return new Promise((resolve, reject) => {
      userReg({ username: username.trim(), password: password, code: code, key: key, org_name: org_name, user_type: user_type, phone: phone, org_status: org_status, contact_name: contact_name }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.access_token)
        commit('SET_TOKEN_TYPE', data.token_type)
        setToken(data.access_token)
        setTokenType(data.token_type)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMyInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        commit('SET_INTRODUCTION', data)
        const { name, avatar } = data
        // roles must be a non-empty array
        // if (!roles || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }

        const system = parseInt(getSystem())
        // console.log(system)
        let roles_name = ''
        switch (system) {
          case 0:
            roles_name = 'trainingManage'
            break
          case 1:
            roles_name = 'businessReview'
            break
          case 2:
            roles_name = 'highSkilledTalentManage'
            break
          case 3:
            roles_name = 'technicalCollegePublicity'
            break
          case 4:
            roles_name = 'systemManage'
            break
          default:
            roles_name = 'trainingManage'
        }
        commit('SET_ROLES', roles_name)

        // commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        // commit('SET_INTRODUCTION', introduction)
        setUserInfo(data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user 侧边栏
  getSidebars({ commit }, state) {
    return new Promise((resolve, reject) => {
      getSidebars().then(response => {
        const { data } = response
        commit('SET_SIDEBARS', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  // logout({ commit, state, dispatch }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       commit('SET_TOKEN', '')
  //       commit('SET_ROLES', [])
  //       removeToken()
  //       resetRouter()

  //       // reset visited views and cached views
  //       // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
  //       dispatch('tagsView/delAllViews', null, { root: true })

  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
